//
//  CourseWebView.m
//  MicroClass
//
//  Created by lxl on 2018/7/26.
//  Copyright © 2018年 lxl. All rights reserved.
//

#import "CourseWebView.h"
#import "ProgressHUD.h"
@implementation CourseWebView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
////计算文字size
//+(CGFloat) boundingRectWithSize:(NSString*) txt Font:(UIFont*) font Size:(CGSize) size{
//
//    CGSize _size;
//
//    NSDictionary *attribute = @{NSFontAttributeName:font};
//
//    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
//
//    _size = [txt boundingRectWithSize:size options: options attributes:attribute context:nil].size;
//    _size.width += 1;
//    _size.height += 1;
//    return _size.height;
//
//}
//- (void)addTheHeaderView{
//    if (!self.str_Title) {
//        return;
//    }
//    CGFloat titleWidth = SCREEN_WIDTH - 30;
//    CGFloat titleHeight = [CourseWebView boundingRectWithSize:self.str_Title Font:[UIFont fontWithName:@"PingFangSC-Medium" size:17] Size:CGSizeMake(titleWidth, 1000)];
//
//
//
//    _headerView = [UIView new];
//    _headerView.backgroundColor = [UIColor whiteColor];
//    self.headerLab = [UILabel new];
//    self.headerLab.numberOfLines = 0;
//    self.headerLab.text = self.str_Title;
//    self.headerLab.font = [UIFont fontWithName:@"PingFangSC-Medium" size:17];
//    self.headerLab.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
//    [self.headerView addSubview:self.headerLab];
//    self.headerLab.frame = CGRectMake(15, 23, titleWidth, titleHeight);
//
//
//    CGFloat imgWidth = 37;
//    _avaterImg = [UIImageView new];
//    _avaterImg.layer.cornerRadius = imgWidth/2;
//    _avaterImg.layer.masksToBounds = YES;
//    _avaterImg.frame = CGRectMake(15, CGRectGetMaxY( self.headerLab.frame) + 22, imgWidth, imgWidth);
//    [self.headerView addSubview:_avaterImg];
//
//
//
//
//    //    [self.descLab setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
//    self.nameLab = [UILabel new];
//    self.nameLab.text = self.str_userName;
//    self.nameLab.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
//    self.nameLab.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
//    [self.headerView addSubview:self.nameLab];
//    self.nameLab.frame = CGRectMake(CGRectGetMaxX(_avaterImg.frame) + 7, CGRectGetMinY(_avaterImg.frame), SCREEN_WIDTH - CGRectGetMaxX(_avaterImg.frame) + 7 - 10, 15);
//
//
//    CGFloat detailWidth  = SCREEN_WIDTH - CGRectGetMaxX(_avaterImg.frame) + 7 - 10;
//    CGFloat detailHeight = [CourseWebView boundingRectWithSize:self.str_headline Font:[UIFont fontWithName:@"PingFangSC-Medium" size:12] Size:CGSizeMake(detailWidth , 1000)];
//
//    self.descLab = [UILabel new];
//    self.descLab.numberOfLines = 0;
//    self.descLab.text = self.str_headline;
//
//    self.descLab.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12];
//    self.descLab.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
//    [self.headerView addSubview:self.descLab];
//    self.descLab.frame = CGRectMake(CGRectGetMinX(self.nameLab.frame), CGRectGetMaxY(_nameLab.frame) + 9,detailWidth, detailHeight);
//
//
//
//    CGFloat headerHeight = CGRectGetMaxY(self.descLab.frame) + 20;
//
//    [self.webview addSubview:_headerView];
//    _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, headerHeight);
//
//
//    self.webview.scrollView.contentInset= UIEdgeInsetsMake(headerHeight,0,0,0);
//
//}
- (WKWebView *)webview{
    if(!_webview){
        _webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH , 50)];
        _webview.scrollView.scrollEnabled = NO;
        //        _webview.scrollView.userInteractionEnabled = NO;
        
        _webview.tag = 1000;
        _webview.navigationDelegate = self;
        //自适应宽高，这句要加
        //        _webview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self addSubview:_webview];
        [_webview.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
        //        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:str_desc]];
        //        [_webview loadRequest:request];
//        [_webview loadHTMLString:str_desc baseURL:nil];
    }
    return _webview;
}
- (void)addTheCourseWebView:(NSString *)str_desc{
    self.str_desc = str_desc;
    if(!_webview){
        _webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH , self.frame.size.height)];
        _webview.scrollView.scrollEnabled = NO;
//        _webview.scrollView.userInteractionEnabled = NO;

        _webview.tag = 1000;
        _webview.navigationDelegate = self;
        //自适应宽高，这句要加
//        _webview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self addSubview:_webview];
        [_webview.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:str_desc]];
//        [_webview loadRequest:request];
    }
    [self.webview loadHTMLString:str_desc baseURL:nil];


    
    if(!_progressView){
        _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,2)];
        _progressView.progressTintColor = [UIColor redColor];
        [_webview addSubview:_progressView];
        _progressView.hidden = YES;
        [_webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];

    }

    _lineView = [UIView new];
    _lineView.frame = CGRectMake(0, CGRectGetMaxY(_webview.frame), SCREEN_WIDTH, 10);
    _lineView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self addSubview:_lineView];
    
    
    
    _commentLab = [UILabel new];
    _commentLab.text = @"评论";
    _commentLab.font = [UIFont fontWithName:@"PingFangSC-Medium" size:17];
    _commentLab.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
    [self addSubview:_commentLab];
    _commentLab.frame = CGRectMake(15, CGRectGetMinY(_lineView.frame) + 17, 200, 20);
    _lineView.hidden = YES;
    _commentLab.hidden = YES;
//    view.backgroundColor = [UIColor redColor];


//    _lineView.frame = CGRectMake(0, CGRectGetMaxY(_webview.frame), SCREEN_WIDTH, 10);
    [ProgressHUD show:@"loading..." inView:self mode:ProgressModeLoading];
    
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [ProgressHUD hide];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [ProgressHUD hide];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 类似 UIWebView 的 －webViewDidFinishLoad:
    if (self.str_desc) {
        NSString *fontSize = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",300];
        [ webView evaluateJavaScript:fontSize completionHandler:nil];
    }
    [ProgressHUD hide];
    NSLog(@"didFinishNavigation");
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@" %s,change = %@",__FUNCTION__,change);
    if ([keyPath isEqual: @"contentSize"] && object == _webview.scrollView) {
        
        //获取网页正文全文高，刷新cell
//        WS(wkSelf)
//        [_webview evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//            wkSelf.webview.frame = CGRectMake(0, 0, SCREEN_WIDTH, [result doubleValue]);//将WKWebView的高度设置为内容高度
//            //刷新制定位置Cell
////            [self refreshWebViewCell];
//            if(wkSelf.changeHeaderViewHeight != nil){
//                wkSelf.changeHeaderViewHeight([result doubleValue]);
//            }
//        }];
        
        CGFloat bottomHeight = 10 + 17 + 20;
        CGFloat websizeHeight = [[change objectForKey:@"new"] CGSizeValue].height ;
        _webview.frame = CGRectMake(15, 0, SCREEN_WIDTH - 30,websizeHeight );
//+ CGRectGetMaxY(_headerView.frame)
        _lineView.frame = CGRectMake(0, CGRectGetMaxY(_webview.frame), SCREEN_WIDTH, 10);
        _commentLab.frame = CGRectMake(15, CGRectGetMaxY(_lineView.frame) + 17, 200, 20);
        _lineView.hidden = NO;
        _commentLab.hidden = NO;
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH , websizeHeight + bottomHeight);
//        self.frame = _webview.frame ;
        if(self.changeHeaderViewHeight != nil){
            self.changeHeaderViewHeight(websizeHeight + bottomHeight);
        }
     
//        webViewHeight = websize.height;
//        [self.course_tab reloadData];

        return;
    }

    if ([keyPath isEqual: @"estimatedProgress"] && object == _webview) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:_webview.estimatedProgress animated:YES];
        if(_webview.estimatedProgress >= 1.0f)
        {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)removeWebViewObserver{
    
    [_webview.scrollView removeObserver:self forKeyPath:@"contentSize"];
    
}

- (void)dealloc{
    NSLog(@"Course dealloc");
    if (_progressView){
        [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
    }
//    if (!isFinished){
        [self removeWebViewObserver];
//    }
    // if you have set either WKWebView delegate also set these to nil here
    [_webview setNavigationDelegate:nil];
    [_webview setUIDelegate:nil];
}
@end
